﻿namespace MicroCloud.EventBuses
{
    /// <summary>
    /// 事件处理器 <see cref="IEventHandler"/> 的可释放包装
    /// </summary>
    public class EventHandlerDisposeWrapper : Disposable
    {
        /// <summary>
        /// 释放活动
        /// <para>封装没有参数且不返回值的方法 <see cref="Action"/></para>
        /// </summary>
        private readonly Action disposeAction;

        /// <summary>
        /// 初始化一个事件处理器 <see cref="IEventHandler"/> 的可释放包装 <see cref="EventHandlerDisposeWrapper"/> 的新实例
        /// </summary>
        /// <param name="eventHandler"></param>
        /// <param name="disposeAction"></param>
        public EventHandlerDisposeWrapper(IEventHandler eventHandler, Action disposeAction = null)
        {
            this.disposeAction = disposeAction;
            EventHandler = eventHandler;
        }

        /// <summary>
        /// 获取或设置 事件处理器对象
        /// </summary>
        public IEventHandler EventHandler { get; set; }

        /// <summary>
        /// 释放资源
        /// </summary>
        /// <param name="disposing"></param>
        protected override void Dispose(bool disposing)
        {
            if (!Disposed)
            {
                disposeAction?.Invoke();
            }
            base.Dispose(disposing);
        }
    }
}